package queue_test;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;


public class Queue_test {

}

/**
 * 402移掉k位数字
 */
class Solution {
    public String removeKdigits(String num, int k) {
        //使用队列进行存储结果
        Deque<Character> deque = new LinkedList<>();

        for (int i = 0;i < num.length();i++){
            char digit = num.charAt(i);

            //如果前一个数字大于后一个就出队列
            if(!deque.isEmpty() && deque.peekLast() > digit && k>0){
                deque.pollLast();
                k--;
            }
            deque.offerLast(digit);
        }

        for(int i = 0;i < k ; i++){
            deque.pollLast();
        }
        StringBuilder ret = new StringBuilder();
        boolean leadingZero = true;
        while (!deque.isEmpty()) {
            char digit = deque.pollFirst();
            if (leadingZero && digit == '0') {
                continue;
            }
            leadingZero = false;
            ret.append(digit);
        }
        return ret.length() == 0 ? "0" : ret.toString();

    }
}